
package com.hy.enterprise.framework.persistence.api;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.springframework.stereotype.Component;

import com.hy.enterprise.framework.lang.LibraRuntimeException;
import com.hy.enterprise.framework.persistence.PersistentException;
import com.hy.enterprise.framework.persistence.api.parameter.ICalendarTemporalParameterValue;
import com.hy.enterprise.framework.persistence.api.parameter.IDateTemporalParameterValue;
import com.hy.enterprise.framework.persistence.api.parameter.ITemporalParameterValue;
import com.hy.enterprise.framework.util.GenericsUtils;
import com.hy.enterprise.framework.util.LibraUtil;
import com.hy.enterprise.framework.util.lang.ClassUtil;
import com.hy.enterprise.framework.util.lang.GenericUtil;
import com.hy.enterprise.framework.util.lang.ReflectionUtil;
import com.hy.enterprise.framework.util.lang.UUIDUtil;
import com.hy.enterprise.framework.util.logger.SeamLoggerUtil;
import com.hy.erp.inventory.pojo.constant.PojoConstants;
import com.hy.mydesktop.shared.persistence.domain.gxt.MyBaseModel;
import com.hy.mydesktop.shared.persistence.domain.util.Persistable;

/**
 * 
 * 
 * <ul>
 * <li>开发作者：花宏宇</li>
 * <li>设计日期：2012-2-4；时间：下午12:13:23</li>
 * <li>类型名称：MyAbstractDao</li>
 * <li>设计目的：抽象数据访问对象实现类</li>
 * </ul>
 * <ul>
 * <b>修订编号：</b>
 * <li>修订日期：</li>
 * <li>修订作者：</li>
 * <li>修订原因：</li>
 * <li>修订内容：</li>
 * </ul>
 */
// @Component("myAbstractDao")
public class MyAbstractDao<PersistentEntity extends Persistable> implements	IDao<PersistentEntity> {
//	public class MyAbstractDao<PersistentEntity extends Serializable> implements	IDao<PersistentEntity> {
	EntityManagerFactory entityManagerFactory = null;
	private Log logger=LogFactory.getLog(MyAbstractDao.class);
	/**
	 * 持久化数据模型类类型
	 */
	@SuppressWarnings("unchecked")
	private Class<PersistentEntity> entityClass = GenericsUtils.getSuperClassGenricType(this.getClass());
	/**
	 * 持久模型管理器
	 */
	EntityManager entityManager;

	public EntityManagerFactory getEntityManagerFactory() {
		return entityManagerFactory;
	}

	// @Resource
	@PersistenceUnit
	public void setEntityManagerFactory(
			EntityManagerFactory entityManagerFactory) {
		this.entityManagerFactory = entityManagerFactory;

	}


	/**
	 * 构造函数
	 */
	public MyAbstractDao() {
		super();
		// this .initGenricType ( ) ;
	}

	/**
	 * 构造函数
	 * 
	 * @param entityClass
	 */
	@SuppressWarnings("unchecked")
	public MyAbstractDao(Class<PersistentEntity> entityClass) {
		super();
		this.entityClass = (Class<PersistentEntity>) LibraUtil
				.getImplementClass(entityClass);
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#batchExecute(boolean,
	 *      java.lang.String, java.util.Map)
	 */
	public Integer batchExecute(boolean isNamedQuery, final String query,
			final Map<String, ?> values) {
		/*
		 * try { Query jpaQuery = null ; if ( isNamedQuery ) { jpaQuery = this
		 * .getEntityManager ( ) .createNamedQuery ( query ) ; } else { jpaQuery
		 * = this .getEntityManager ( ) .createQuery ( query ) ; } this
		 * .populateParameters ( jpaQuery , values ) ; return jpaQuery
		 * .executeUpdate ( ) ; } catch ( Exception exception ) { SeamLoggerUtil
		 * .error ( MyAbstractDao.logger , "在执行批处理操作时产生异常：" + exception ) ;
		 * return 0 ; }
		 */
		return 0;
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#batchExecute(boolean,
	 *      java.lang.String, java.lang.Object[])
	 */
	public Integer batchExecute(boolean isNamedQuery, final String query,
			final Object... values) {
		/*
		 * try { Query jpaQuery = null ; if ( isNamedQuery ) { jpaQuery = this
		 * .getEntityManager ( ) .createNamedQuery ( query ) ; } else { jpaQuery
		 * = this .getEntityManager ( ) .createQuery ( query ) ; } this
		 * .populateParameters ( jpaQuery , values ) ; return jpaQuery
		 * .executeUpdate ( ) ; } catch ( Exception exception ) { SeamLoggerUtil
		 * .error ( MyAbstractDao.logger , "在执行批处理操作时产生异常：" + exception ) ;
		 * return 0 ; }
		 */
		return 0;
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#clear()
	 */
	@Override
	public void clear() {
		this.getEntityManager().flush();
		this.getEntityManager().flush();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#contains(com.hy.enterprise.framework.persistence.api.Persistable)
	 */
	@Override
	public boolean contains(PersistentEntity persistentEntity)
			throws PersistentException {
		if ((null == persistentEntity)
				|| (null == persistentEntity.getIdentifier())) {
			return false;
		} else {
			return this.contains(persistentEntity.getIdentifier());
		}
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#contains(java.io.Serializable)
	 */
	@Override
	public boolean contains(String identifier) throws PersistentException {
		if (null == identifier) {
			return false;
		} else {
			return (null != this.find(identifier));
		}
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#count()
	 */
	@Override
	public Integer count() {
		StringBuffer jpql = new StringBuffer();
		jpql.append("SELECT COUNT(o.identifier) FROM "
				+ this.getPersistentEneityClass().getName() + " AS o");
		return ((Long) this.getEntityManager().createQuery(jpql.toString())
				.getSingleResult()).intValue();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#count(java.lang.String,
	 *      boolean)
	 */
	@Override
	public Integer count(String query, boolean isNamedQuery) {
		if (isNamedQuery) {
			return (Integer) this.getEntityManager().createNamedQuery(query)
					.getSingleResult();
		} else {
			return (Integer) this.getEntityManager().createQuery(query)
					.getSingleResult();
		}
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#countByNamedQuery(java.lang.String,
	 *      java.util.Map)
	 */
	@Override
	public Integer countByNamedQuery(String queryName, Map<String, ?> parameters) {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		this.populateParameters(query, parameters);
		return (Integer) query.getSingleResult();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#countByNamedQuery(java.lang.String,
	 *      java.lang.Object[])
	 */
	@Override
	public Integer countByNamedQuery(String queryName, Object... parameters) {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		this.populateParameters(query, parameters);
		return (Integer) query.getSingleResult();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#countByQuery(java.lang.String,
	 *      java.util.Map)
	 */
	public Integer countByQuery(String query, Map<String, ?> parameters) {
		Query jpaQuery = this.getEntityManager().createQuery(query);
		this.populateParameters(jpaQuery, parameters);
		return (Integer) jpaQuery.getSingleResult();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#countByQuery(java.lang.String,
	 *      java.lang.Object[])
	 */
	public Integer countByQuery(String query, Object... parameters) {
		Query jpaQuery = this.getEntityManager().createQuery(query);
		this.populateParameters(jpaQuery, parameters);
		return (Integer) jpaQuery.getSingleResult();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#find()
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> find() throws PersistentException {
		return this
				.getEntityManager()
				.createQuery(
						"SELECT o FROM " + this.getPersistentEneityClass().getName() + " AS o ")
						//"SELECT * FROM " + "" + " AS o ")
				.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#find(int, int)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> find(int first, int max)
			throws PersistentException {
		Query query = this.getEntityManager().createQuery(
				"FROM " + this.getPersistentEneityClass().getSimpleName() + " AS o ");
		query.setFirstResult(first);
		query.setMaxResults(max);
		System.err.println(query.toString());
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#find(int, int,
	 *      java.lang.String, java.lang.Object[])
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> find(int first, int max,
			String queryString, Object... values) throws PersistentException {
		Query query = this.getEntityManager().createQuery(queryString);
		this.populateParameters(query, values);
		query.setFirstResult(first);
		query.setMaxResults(max);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#find(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> find(String queryString)
			throws PersistentException {
		return this.getEntityManager().createQuery(queryString).getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#find(java.lang.String,
	 *      int, int)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> find(String queryString, int first,
			int max) throws PersistentException {
		Query query = this.getEntityManager().createQuery(queryString);
		query.setFirstResult(first);
		query.setMaxResults(max);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#find(java.lang.String,
	 *      java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> find(String queryString,
			Map<String, ?> parameters) throws PersistentException {
		Query query = this.getEntityManager().createQuery(queryString);
		this.populateParameters(query, parameters);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#find(java.lang.String,
	 *      java.util.Map, int, int)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> find(String queryString,
			Map<String, ?> parameters, int first, int max)
			throws PersistentException {
		Query query = this.getEntityManager().createQuery(queryString);
		this.populateParameters(query, parameters);
		query.setFirstResult(first);
		query.setMaxResults(max);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#find(java.lang.String,
	 *      java.lang.Object[])
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> find(String queryString,
			Object... values) throws PersistentException {
		Query query = this.getEntityManager().createQuery(queryString);
		this.populateParameters(query, values);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findByExample(java.lang.Object)
	 */
	@SuppressWarnings("unchecked")
	public <T extends Serializable> List<T> findByExample(Object exampleInstance) {
		Criteria criteria = this.getHibernateSession().createCriteria(
				this.getPersistentEneityClass());
		Example example = Example.create(exampleInstance);
		criteria.add(example);
		return criteria.list();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findByExample(java.io.Serializable,
	 *      java.lang.String[])
	 */
	@SuppressWarnings("unchecked")
	public <T extends Serializable> List<T> findByExample(T exampleInstance,
			String[] excludeProperty) {
		Criteria criteria = this.getHibernateSession().createCriteria(
				this.getPersistentEneityClass());
		Example example = Example.create(exampleInstance);
		for (String exclude : excludeProperty) {
			example.excludeProperty(exclude);
		}
		criteria.add(example);
		return criteria.list();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#find(java.io.Serializable)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public PersistentEntity findByIdentifier(String identifier)
			throws PersistentException {
		//return this.getEntityManager().find(this.getPersistentEneityClass(),identifier);
		
		String queryString=	"SELECT o FROM " + this.getPersistentEneityClass().getName() 
			+ " AS o where o.identifier=:identifier";
		Query query = this.getEntityManager().createQuery(queryString);
		query.setParameter("identifier", identifier);
		return (PersistentEntity)query.getSingleResult();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findByIdentifier(java.lang.String[])
	 */
	@SuppressWarnings("unchecked")
	public <T extends Serializable> List<T> findByIdentifier(String... identifiers)
			throws PersistentException {
		if ((null == identifiers) || (identifiers.length == 0)) {
			return null;
		} else {
			StringBuffer jpql = new StringBuffer();

			String entityPath = this.getPersistentEneityClass().toString();
			int ind = entityPath.lastIndexOf(".");
			String Entity = entityPath.substring(ind + 1);
			jpql.append("SELECT o FROM "
					+ this.getPersistentEneityClass()
							.toString()
							.substring(
									5,
									this.getPersistentEneityClass().toString()
											.length())
					+ " AS o WHERE o.identifier IN(");
			int entityCount = identifiers.length;
			for (int index = 0; index < entityCount; index++) {
				String identifier = identifiers[index];
				if (null != identifier) {
					if (index == entityCount) {
						jpql.append("'" + identifier + "' ) ");
					} else {
						jpql.append("'" + identifier + "' , ");
					}
				}
			}
			if (jpql.toString().endsWith(", ")) {
				jpql.delete(jpql.length() - 2, jpql.length());
				jpql.append(") ");
			}
			return this.getEntityManager().createQuery(jpql.toString())
					.getResultList();
		}
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public PersistentEntity findById(String id) throws PersistentException {
		 
		String queryString=	"SELECT o FROM " + this.getPersistentEneityClass().getName() 
			+ " AS o where o.id=:id";
		 Query query = this.getEntityManager().createQuery(queryString);
		 query.setParameter("id", id);
			return (PersistentEntity)query.getSingleResult();
	}

	@Override
	public <T extends Serializable> List<T> findById(String... id)
			throws PersistentException {
		throw new RuntimeException("该方法未实现");
		//return null;
	}
	
	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findByNamedParams(java.lang.String,
	 *      java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> findByNamedParams(
			String queryString, Map<String, ?> parameters)
			throws PersistentException {
		Query query = this.getEntityManager().createQuery(queryString);
		this.populateParameters(query, parameters);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findByNamedParams(java.lang.String,
	 *      java.util.Map, int, int)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> findByNamedParams(
			String queryString, Map<String, ?> parameters, int first, int max)
			throws PersistentException {
		Query query = this.getEntityManager().createQuery(queryString);
		this.populateParameters(query, parameters);
		query.setFirstResult(first);
		query.setMaxResults(max);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findByNamedQuery(int,
	 *      int, java.lang.String, java.lang.Object[])
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> findByNamedQuery(int first,
			int max, String queryName, Object... values)
			throws PersistentException {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		this.populateParameters(query, values);
		query.setFirstResult(first);
		query.setMaxResults(max);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findByNamedQuery(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> findByNamedQuery(String queryName)
			throws PersistentException {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findByNamedQuery(java.lang.String,
	 *      int, int)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> findByNamedQuery(String queryName,
			int first, int max) throws PersistentException {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		query.setFirstResult(first);
		query.setMaxResults(max);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findByNamedQuery(java.lang.String,
	 *      java.lang.Object[])
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> findByNamedQuery(String queryName,
			Object... values) throws PersistentException {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		this.populateParameters(query, values);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findByNamedQueryAndNamedParams(java.lang.String,
	 *      java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> findByNamedQueryAndNamedParams(
			String queryName, Map<String, ?> parameters)
			throws PersistentException {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		this.populateParameters(query, parameters);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findByNamedQueryAndNamedParams(java.lang.String,
	 *      java.util.Map, int, int)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> List<T> findByNamedQueryAndNamedParams(
			String queryName, Map<String, ?> parameters, int first, int max)
			throws PersistentException {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		this.populateParameters(query, parameters);
		query.setFirstResult(first);
		query.setMaxResults(max);
		return query.getResultList();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findUniqueResult(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> T findUniqueResult(String queryString)
			throws PersistentException {
		return (T) this.getEntityManager().createQuery(queryString)
				.getSingleResult();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findUniqueResult(java.lang.String,
	 *      java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> T findUniqueResult(String queryString,
			Map<String, ?> parameters) throws PersistentException {
		Query query = this.getEntityManager().createQuery(queryString);
		this.populateParameters(query, parameters);
		return (T) query.getSingleResult();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findUniqueResult(java.lang.String,
	 *      java.lang.Object[])
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> T findUniqueResult(String queryString,
			Object... values) throws PersistentException {
		Query query = this.getEntityManager().createQuery(queryString);
		this.populateParameters(query, values);
		return (T) query.getSingleResult();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findUniqueResultByNamedParams(java.lang.String,
	 *      java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> T findUniqueResultByNamedParams(
			String queryName, Map<String, ?> parameters)
			throws PersistentException {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		this.populateParameters(query, parameters);
		return (T) query.getSingleResult();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findUniqueResultByNamedQuery(java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> T findUniqueResultByNamedQuery(
			String queryName) throws PersistentException {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		return (T) query.getSingleResult();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findUniqueResultByNamedQuery(java.lang.String,
	 *      java.lang.Object[])
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> T findUniqueResultByNamedQuery(
			String queryName, Object... values) throws PersistentException {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		this.populateParameters(query, values);
		return (T) query.getSingleResult();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#findUniqueResultByNamedQueryAndNamedParams(java.lang.String,
	 *      java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Serializable> T findUniqueResultByNamedQueryAndNamedParams(
			String queryName, Map<String, ?> parameters)
			throws PersistentException {
		Query query = this.getEntityManager().createNamedQuery(queryName);
		this.populateParameters(query, parameters);
		return (T) query.getSingleResult();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#flush()
	 */
	@Override
	public void flush() throws PersistentException {
		this.getEntityManager().flush();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#flushAndClear()
	 */
	public void flushAndClear() {
		this.getEntityManager().flush();
		this.getEntityManager().clear();
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#getEntityManager()
	 */
	@Override
	public EntityManager getEntityManager() {
		if (entityManagerFactory == null) {
			throw new PersistentException(
					"entityManagerFactory为空，不能创建entityManager");
		} /*
		 * else {
		 * 
		 * entityManager = entityManagerFactory.createEntityManager(); }
		 */
		return this.entityManager;
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#getPersistentEneityClass()
	 */
	@Override
	public Class<PersistentEntity> getPersistentEneityClass() {
		return this.entityClass;
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#getReference(java.io.Serializable)
	 */
	@Override
	public PersistentEntity getReference(String identifier)
			throws PersistentException {
		return this.getEntityManager().getReference(
				this.getPersistentEneityClass(), identifier);
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#isPropertyUnique(java.lang.String,
	 *      java.lang.Object, java.lang.Object)
	 */
	public boolean isPropertyUnique(final String propertyName,
			final Object newValue, final Object oldValue) {
		Object propertyValue = null;
		if (null == newValue) {
			propertyValue = oldValue;
		} else if (newValue == oldValue) {
			propertyValue = oldValue;
		} else {
			propertyValue = newValue;
		}
		StringBuffer jpql = new StringBuffer();
		jpql.append("SELECT COUNT(o.identifier) FROM "
				+ this.getPersistentEneityClass() + " AS o WHERE o."
				+ propertyName + " = ? ");
		Query query = this.getEntityManager().createQuery(jpql.toString());
		this.populateParameters(query, propertyValue);
		return ((Integer) query.getSingleResult()) > 1;
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#merge(com.hy.enterprise.framework.persistence.api.Persistable)
	 */
	@Override
	public PersistentEntity merge(PersistentEntity persistentEntity)
			throws PersistentException {
		return this.getEntityManager().merge(persistentEntity);
	}
	
	@Override
	public String[] merge(PersistentEntity... persistentEntities)
			throws PersistentException {
		Integer count = new Integer(0);
		String[] id = new String[persistentEntities.length];
		for (PersistentEntity persistentEntity : persistentEntities) {
			if (this.merge(persistentEntity)!=null) {
				id[count++] = persistentEntity.getIdentifier();

			}
		}
		return id;
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#persist(com.hy.enterprise.framework.persistence.api.Persistable)
	 */
	@Override
	public boolean persist(PersistentEntity persistentEntity)
			throws PersistentException {
		boolean result = false;
		if (persistentEntity.getIdentifier() == null
				|| persistentEntity.getIdentifier().equals("")) {
			persistentEntity.setIdentifier(UUIDUtil.randomUUID());
			logger.debug("为实体 "+persistentEntity+"分配一个Identifier:"+persistentEntity.getIdentifier());

		}
		System.err.println(getEntityManager());
		getEntityManager().persist(persistentEntity);
		// entityManager = this.getEntityManagerFactory().createEntityManager();
		// entityManager.persist ( persistentEntity ) ;
		// this .getEntityManager ( ).flush ( ) ;
		// entityManager.flush ( ) ;
		result = true;
		try {
		} catch (Exception exception) {
			throw new PersistentException("持久化数据模型时发生错误");
		}

		return result;
	}

	@Override
	public String[] persist(PersistentEntity... persistentEntities)
			throws PersistentException {
		Integer count = new Integer(0);
		String[] id = new String[persistentEntities.length];
		for (PersistentEntity persistentEntity : persistentEntities) {
			if (this.persist(persistentEntity)) {
				id[count++] = persistentEntity.getIdentifier();

			}
		}
		return id;
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#persist(PersistentEntity[])
	 */
	@Override
	public Integer persists(PersistentEntity... persistentEntities)
			throws PersistentException {

		Integer count = new Integer(0);
		for (PersistentEntity persistentEntity : persistentEntities) {
			if (this.persist(persistentEntity)) {
				count++;
			}
		}
		return new Integer(count);
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#refresh(com.hy.enterprise.framework.persistence.api.Persistable)
	 */
	@Override
	public void refresh(PersistentEntity persistentEntity)
			throws PersistentException {
		this.getEntityManager().refresh(persistentEntity);
	}
	
	@Override
	public void cascadeRemove(PersistentEntity persistentEntity)
			throws PersistentException {
		getEntityManager().remove(persistentEntity);

		//return false;
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#remove(com.hy.enterprise.framework.persistence.api.Persistable)
	 */
	@Override
	public boolean remove(PersistentEntity persistentEntity)
			throws PersistentException {
		if ((null == persistentEntity)
				|| (null == persistentEntity.getIdentifier())) {
			return false;
		} else {
			StringBuffer jpql = new StringBuffer();
			/**
			 * .createQuery(
						"SELECT o FROM " + this.getPersistentEneityClass().getName() + " AS o ")
						//"SELECT * FROM " + "" + " AS o ")
			 */
			jpql.append("DELETE FROM " + this.getPersistentEneityClass().getName()
					+ " AS o WHERE o.identifier = :identifier");
			return this
					.getEntityManager()
					.createQuery(jpql.toString())
					.setParameter("identifier",
							persistentEntity.getIdentifier()).executeUpdate() == 1;
		}
	}

	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#remove(PersistentEntity[])
	 */
	@Override
	public Integer remove(PersistentEntity... persistentEntities)
			throws PersistentException {
		if ((null == persistentEntities) || (persistentEntities.length == 0)) {
			return new Integer(0);
		} else {
			StringBuffer jpql = new StringBuffer();
			jpql.append("DELETE FROM " + this.getPersistentEneityClass()
					+ " AS o WHERE o.identifier IN (");
			int entityCount = persistentEntities.length;
			for (int index = 0; index < entityCount; index++) {
				PersistentEntity persistentEntity = persistentEntities[index];
				if (null != persistentEntity.getIdentifier()) {
					if (index == entityCount) {
						jpql.append("'" + persistentEntity.getIdentifier()
								+ "' ) ");
					} else {
						jpql.append("'" + persistentEntity.getIdentifier()
								+ "' , ");
					}
				}
			}
			if (jpql.toString().endsWith(", ")) {
				jpql.delete(jpql.length() - 2, jpql.length());
				jpql.append(") ");
			}

			return this.getEntityManager().createQuery(jpql.toString())
					.executeUpdate();
		}
	}

	
	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#remove(java.io.Serializable)
	 */
	@Override
	public boolean remove(String identifier) throws PersistentException {
		try {
			this.getEntityManager().remove(this.find(identifier));
		} catch (Exception exception) {
			throw new PersistentException("在移除标识符为：[" + identifier
					+ "]的持久化数据模型时发生错误", exception);
		}
		return true;
	}

	@Override
	public boolean removeById(String id) throws PersistentException {
		try {
			this.getEntityManager().remove(this.findById(id));
		} catch (Exception exception) {
			throw new PersistentException("在移除标识符为：[" + id
					+ "]的持久化数据模型时发生错误", exception);
		}
		return true;
	}
	/**
	 * @see com.hy.enterprise.framework.persistence.api.IDao#remove(ID[])
	 */
	@Override
	public Integer remove(String... identifiers) throws PersistentException {
		if ((null == identifiers) || (identifiers.length == 0)) {
			return new Integer(0);
		} else {
			StringBuffer jpql = new StringBuffer();

			String entityPath = this.getPersistentEneityClass().toString();
			int ind = entityPath.lastIndexOf(".");
			String Entity = entityPath.substring(ind + 1);
			System.out.println(Entity + "vvvvvvvvvvvvvvvvvvvSSSSSSSSSSSSSS");
			jpql.append("DELETE FROM " + Entity
					+ " AS o WHERE o.identifier IN (");

			int entityCount = identifiers.length;
			for (int index = 0; index < entityCount; index++) {
				String identifier = identifiers[index];
				if (null != identifier) {
					if (index == entityCount) {
						jpql.append("'" + identifier + "' ) ");
					} else {
						jpql.append("'" + identifier + "' , ");
					}
				}
			}
			if (jpql.toString().endsWith(", ")) {
				jpql.delete(jpql.length() - 2, jpql.length());
				jpql.append(") ");
			}
			logger.debug("************************************************");
			logger.debug(jpql.toString() );
			logger.debug("************************************************");
			return this.getEntityManager().createQuery(jpql.toString())	.executeUpdate();
		}
	}
	
	@ Override
	public boolean submitPersistentEntities (List<MyBaseModel> persistentEntities )
	{
		MyBaseModel baseModel = null;
		Object object=null;
		try {
			for (MyBaseModel persistentEntity : persistentEntities) {
				for (String pro : persistentEntity.getPropertyNames()) {
					logger.debug("属性名称："+pro+",属性值："+persistentEntity.get(pro));
				}
				object=Class.forName(entityClass.getName()).newInstance();
				baseModel=(MyBaseModel)object;
				baseModel.setProperties(persistentEntity.getProperties());
				//MyBaseModel baseModel=(MyBaseModel)persistentEntity;
				if (baseModel.get(PojoConstants.ENTITY_STATUS)==null) {
					this.merge((PersistentEntity)baseModel);
				} else {
					if (baseModel.get(PojoConstants.ENTITY_STATUS).equals(PojoConstants.PERSIST_STATUS)) {
						this.persist((PersistentEntity)baseModel);
					} else if (baseModel.get(PojoConstants.ENTITY_STATUS).equals(PojoConstants.MERGE_STATUS)) {
						this.merge((PersistentEntity)baseModel);
					} else if (baseModel.get(PojoConstants.ENTITY_STATUS).equals(PojoConstants.REMOVE_STATUS)) {
						this.remove((PersistentEntity)baseModel);
					} else {
						throw new RuntimeException("sssssssssssssssssssss");

					}

				}
				//下一次，重新为baseModel之前，先清空数据
				//baseModel=(MyBaseModel)object;
				
			}
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return true;
		
	}
	
	
	@ Override
	public boolean submitPersistentEntities (MyBaseModel... persistentEntities )
	{
		for (MyBaseModel persistentEntity : persistentEntities) {
			MyBaseModel baseModel=(MyBaseModel)persistentEntity;
			if (baseModel.get(PojoConstants.ENTITY_STATUS)==null) {
				this.merge((PersistentEntity)baseModel);
			} else {
				if (baseModel.get(PojoConstants.ENTITY_STATUS).equals(PojoConstants.PERSIST_STATUS)) {
					this.persist((PersistentEntity)baseModel);
				} else if (baseModel.get(PojoConstants.ENTITY_STATUS).equals(PojoConstants.MERGE_STATUS)) {
					this.merge((PersistentEntity)baseModel);
				} else if (baseModel.get(PojoConstants.ENTITY_STATUS).equals(PojoConstants.REMOVE_STATUS)) {
					this.remove((PersistentEntity)baseModel);
				} else {
					throw new RuntimeException("sssssssssssssssssssss");

				}

			}
			
		}
		return true;
		
	}

	/**
	 * <ul>
	 * <li>设计作者：刘川</li>
	 * <li>设计日期：2009-8-8</li>
	 * <li>设计时间：上午09:42:14</li>
	 * <li>设计目的：用于调试JPQL语句的便捷助手类</li>
	 * </ul>
	 * <ul>
	 * <b>修订历史</b>
	 * <li>1、</li>
	 * </ul>
	 * 
	 * @param logger
	 * @param object
	 */
	private void debugJpql(
	 Log logger ,
			Object object) {
		
		  if ( null == object ) { return ; } else if ( object instanceof String
		  ) { SeamLoggerUtil .debug ( logger , "所生成的JPQL查询为：" + object ) ; }
		  else if ( object instanceof StringBuffer ) { SeamLoggerUtil .debug (
		  logger , "所生成的JPQL查询为：" + ( ( StringBuffer ) object ) .toString ( ) )
		  ; }
		 
	}

	/**
	 * <ul>
	 * <li>设计作者：刘川</li>
	 * <li>设计日期：2009-8-8</li>
	 * <li>设计时间：上午08:48:24</li>
	 * <li>设计目的：初始化数据访问对象泛型参数字段</li>
	 * </ul>
	 * <ul>
	 * <b>修订历史</b>
	 * <li>1、</li>
	 * </ul>
	 */
	@SuppressWarnings("unchecked")
	private void initGenricType() {
		this.entityClass = (Class<PersistentEntity>) LibraUtil
				.getImplementClass(ReflectionUtil.getSuperClassGenricType(
						this.getClass(), 0));
	}

	/**
	 * <ul>
	 * <li>设计作者：刘川</li>
	 * <li>设计日期：2009-8-14</li>
	 * <li>设计时间：下午03:52:50</li>
	 * <li>设计目的：</li>
	 * </ul>
	 * <ul>
	 * <b>修订历史</b>
	 * <li>1、</li>
	 * </ul>
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected PersistentEntity createEmptyEntity() {
		String entityClassName = LibraUtil.getImplementClass(
				this.getPersistentEneityClass()).getName();
		try {
			if (null == entityClassName) {
				// SeamLoggerUtil.warn(MyAbstractDao.logger, "无法创建类型名称为空的实体类");
				throw new LibraRuntimeException("无法创建类型名称为空的实体类");
			}
			return (PersistentEntity) ClassUtil.newInstance(entityClassName);
		} catch (ClassNotFoundException classNotFoundException) {
			/*
			 * SeamLoggerUtil.error(MyAbstractDao.logger, "创建空实体类失败",
			 * classNotFoundException);
			 */
			throw new LibraRuntimeException("创建空实体类失败", classNotFoundException);
		} catch (InstantiationException instantiationException) {
			/*
			 * SeamLoggerUtil .error ( MyAbstractDao.logger , "创建空实体类失败" ,
			 * instantiationException ) ;
			 */
			throw new LibraRuntimeException("创建空实体类失败", instantiationException);
		} catch (IllegalAccessException illegalAccessException) {
			/*
			 * SeamLoggerUtil.error(MyAbstractDao.logger, "创建空实体类失败",
			 * illegalAccessException);
			 */throw new LibraRuntimeException("创建空实体类失败",
					illegalAccessException);
		}
	}

	/**
	 * <ul>
	 * <li>设计作者：刘川</li>
	 * <li>设计日期：2009-8-8</li>
	 * <li>设计时间：上午11:22:18</li>
	 * <li>设计目的：在JPA下获取Hibernate Session的辅助方法</li>
	 * </ul>
	 * <ul>
	 * <b>修订历史</b>
	 * <li>1、</li>
	 * </ul>
	 * 
	 * @return
	 */
	protected Session getHibernateSession() {
		return (Session) this.getEntityManager().getDelegate();
	}

	/**
	 * <ul>
	 * <li>设计作者：刘川</li>
	 * <li>设计日期：2009-8-8</li>
	 * <li>设计时间：上午12:49:55</li>
	 * <li>设计目的：组装查询参数</li>
	 * </ul>
	 * <ul>
	 * <b>修订历史</b>
	 * <li>1、</li>
	 * </ul>
	 * 
	 * @param query
	 * @param parameters
	 * @return
	 */
	protected Query populateParameters(Query query, Map<String, ?> parameters) {
		if ((null == query) || (null == parameters) || (parameters.size() == 0)) {
			return null;
		} else {
			for (Map.Entry<String, ?> parameterEntry : parameters.entrySet()) {
				if (parameterEntry.getValue() instanceof ITemporalParameterValue) {
					if (parameterEntry.getValue() instanceof IDateTemporalParameterValue) {
						query.setParameter(parameterEntry.getKey(),
								((IDateTemporalParameterValue) parameterEntry
										.getValue()).getTemporalValue(),
								((IDateTemporalParameterValue) parameterEntry
										.getValue()).getTemporalType());
					} else if (parameterEntry.getValue() instanceof ICalendarTemporalParameterValue) {
						query.setParameter(
								parameterEntry.getKey(),
								((ICalendarTemporalParameterValue) parameterEntry
										.getValue()).getTemporalValue(),
								((ICalendarTemporalParameterValue) parameterEntry
										.getValue()).getTemporalType());
					} else {
						throw new PersistentException("时间、日期参数类型不匹配");
					}
				} else {
					query.setParameter(parameterEntry.getKey(),
							parameterEntry.getValue());
				}
			}
			return query;
		}
	}

	/**
	 * <ul>
	 * <li>设计作者：刘川</li>
	 * <li>设计日期：2009-8-8</li>
	 * <li>设计时间：上午12:50:51</li>
	 * <li>设计目的：组装查询参数</li>
	 * </ul>
	 * <ul>
	 * <b>修订历史</b>
	 * <li>1、</li>
	 * </ul>
	 * 
	 * @param query
	 * @param parameters
	 * @return
	 */
	protected Query populateParameters(Query query, Object... parameters) {
		if ((null == query) || (null == parameters) || (parameters.length == 0)) {
			return null;
		} else {
			int count = parameters.length;
			for (int index = 0; index < count; index++) {
				Object parameter = parameters[index];
				if (parameter instanceof ITemporalParameterValue) {
					if (parameter instanceof IDateTemporalParameterValue) {
						query.setParameter(index,
								((IDateTemporalParameterValue) parameter)
										.getTemporalValue(),
								((IDateTemporalParameterValue) parameter)
										.getTemporalType());
					} else if (parameter instanceof ICalendarTemporalParameterValue) {
						query.setParameter(index,
								((ICalendarTemporalParameterValue) parameter)
										.getTemporalValue(),
								((ICalendarTemporalParameterValue) parameter)
										.getTemporalType());
					} else {
						throw new PersistentException("时间、日期参数类型不匹配");
					}
				} else {
					query.setParameter(index, parameter);
				}
			}
			return query;
		}
	}

	/**
	 * <ul>
	 * <li>设计作者：刘川</li>
	 * <li>设计日期：2009-8-7</li>
	 * <li>设计时间：下午11:38:26</li>
	 * <li>设计目的：由Seam框架用来注入持久模型管理器</li>
	 * </ul>
	 * <ul>
	 * <b>修订历史</b>
	 * <li>1、</li>
	 * </ul>
	 * 
	 * @param entityManager
	 */
	// @ In
	// @Resource
	@PersistenceContext
	protected void setEntityManager(EntityManager entityManager) {

		this.entityManager = entityManager;
	}

	

	

	
}
